/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useEffect, useMemo } from "react";
import {
  Row,
  Col,
  Button,
  Modal,
  List,
  InputNumber,
  Checkbox,
  Form,
  Input,
  message,
  Popconfirm,
  Switch,
} from "antd";
import propTypes from "prop-types";
import { connect } from "dva";

const FormItem = Form.Item;

const formatter = value => {
  if (!value) return 0;
  return !isNaN(value) ? String(value).replace(/^0(0+)|[^\d]+/g, "") : 0;
};

const SettingModal = props => {
  const {
    visible = false,
    showModal = () => {},
    title = "",
    open: openStatus = false, // 功能是否开启
    dispatch,
    form,
    type,
    loadingOpenScore,
    loadingOpenPay,
  } = props;
  const { getFieldDecorator, validateFields, setFieldsValue, isFieldsTouched } = form;
  // 是否展示云店账号绑定的表单输入
  const [isCheck, setCheck] = useState(false);
  const [checkBoxDisabled, setCheckBoxDisabled] = useState(false);
  // 是否已绑定云店账号
  const [isBindCloud, setIsBindCloud] = useState(false);
  const [scoreDetail, setScoreDetail] = useState({});
  const [open, setOpen] = useState(openStatus);

  const listData = useMemo(
    () => [
      {
        content: "平台积分（默认积分名称，不超过6个字）",
        name: "integral_name",
        key: 0,
        type: "input",
        value: scoreDetail.integral_name,
      },
      {
        content: "新用户赠送积分",
        name: "new_user",
        key: 1,
        value: scoreDetail.new_user ? scoreDetail.new_user.point : 0,
        status: scoreDetail.new_user ? scoreDetail.new_user.status : 1,
      },
      {
        content: "绑定手机号赠送积分",
        name: "bind_phone",
        key: 2,
        value: scoreDetail.bind_phone ? scoreDetail.bind_phone.point : 0,
        status: scoreDetail.bind_phone ? scoreDetail.bind_phone.status : 1,
      },
      {
        content: "在线支付赠送积分",
        name: "online_pay",
        key: 3,
        value: scoreDetail.online_pay ? scoreDetail.online_pay.point : 0,
        status: scoreDetail.online_pay ? scoreDetail.online_pay.status : 1,
      },
    ],
    [scoreDetail]
  );

  // 获取积分设置详情
  const getDetail = useCallback(
    () => {
      dispatch({
        type: "wxSettings/wxGetScoreDetail",
      }).then(({ cloud_name, site_id, new_user, bind_phone, online_pay, integral_name }) => {
        setFieldsValue({
          isChecked: !!cloud_name,
        });
        setCheck(!!cloud_name);
        setCheckBoxDisabled(!!cloud_name);
        setIsBindCloud(!!cloud_name);
        setScoreDetail(prevDetail => {
          return {
            ...prevDetail,
            cloud_name,
            site_id,
            new_user,
            bind_phone,
            online_pay,
            integral_name,
          };
        });
      });
    },
    [dispatch, setFieldsValue]
  );

  useEffect(
    () => {
      // 功能开启，获取积分详情
      setOpen(openStatus);
      if (openStatus && visible) {
        getDetail();
      }
    },
    [getDetail, openStatus, visible]
  );

  // 开启所有积分功能
  const openScore = useCallback(
    status => {
      dispatch({
        type: "wxSettings/wxOpenScore",
        payload: {
          status: status ? 2 : 1,
        },
      }).then(() => {
        setOpen(true);
        dispatch({
          type: "wxSettings/wxGetSettingList",
        });
      });
    },
    [dispatch]
  );

  // 开启在线支付
  const onPayClick = useCallback(
    pay_status => {
      dispatch({
        type: "wxSettings/wxOnlinePay",
        payload: {
          pay_status: pay_status ? 2 : 1, // 1：开启，2：关闭
        },
      }).then(() => {
        dispatch({
          type: "wxSettings/wxGetSettingList",
        });
        showModal(false);
      });
    },
    [dispatch, showModal]
  );

  const onCheckBoxCheck = useCallback(
    e => {
      const { checked } = e.target;
      setCheck(checked);
      !checked &&
        setFieldsValue({
          account: "",
          passWord: "",
        });
    },
    [setFieldsValue]
  );

  // 积分修改
  const onInputChange = useCallback(
    (e, field) => {
      setFieldsValue({
        [field]: e.target.value,
      });
    },
    [setFieldsValue]
  );

  // 绑定/解绑云店
  const handleBind = useCallback(
    sign => {
      validateFields((err, fieldsValue) => {
        if (err) return;
        const { account, passWord } = fieldsValue;

        dispatch({
          type: "wxSettings/wxScoreBind",
          payload: {
            cloud_name: account,
            cloud_password: passWord,
            sign, // 1:绑定，2：解绑
          },
        }).then(() => {
          getDetail();
          setFieldsValue({
            account: "",
            passWord: "",
          });
        });
      });
    },
    [dispatch, validateFields, getDetail, setFieldsValue]
  );

  // 关闭/开启当前积分功能
  const onCloseOrOpenScore = useCallback((name, status, point) => {
    setScoreDetail(prevDetail => {
      return {
        ...prevDetail,
        [name]: {
          point,
          status,
        },
      };
    });
  }, []);

  // 保存设置
  const onSave = useCallback(
    () => {
      const validateFieldsArr = [
        "new_user",
        "bind_phone",
        "online_pay",
        "new_user_status",
        "bind_phone_status",
        "online_pay_status",
        "integral_name",
      ];
      if (isCheck) {
        validateFieldsArr.push("isChecked", "account", "passWord");
        // isBindCloud：当用户点击解绑时需要对账号密码做验证
        if (checkBoxDisabled && isBindCloud) {
          validateFieldsArr.splice(7, 3);
        }
      }
      const isTouched = isFieldsTouched(validateFieldsArr);

      validateFields(validateFieldsArr, (err, values) => {
        const {
          isChecked,
          account,
          passWord,
          new_user_status,
          bind_phone_status,
          online_pay_status,
          ...rest
        } = values;
        if (err) return;
        if (account || passWord) {
          message.error("请先提交绑定后再保存设置");
          return;
        }
        // 表单未修改则退出
        if (!isTouched) {
          showModal(false);
          return;
        }
        dispatch({
          type: "wxSettings/wxSaveScore",
          payload: {
            new_user_status: new_user_status ? 1 : 2,
            bind_phone_status: bind_phone_status ? 1 : 2,
            online_pay_status: online_pay_status ? 1 : 2,
            ...rest,
          },
        }).then(() => {
          dispatch({
            type: "wxSettings/wxGetSettingList",
          });
          showModal(false);
        });
      });
    },
    [validateFields, dispatch, showModal, isCheck, checkBoxDisabled, isFieldsTouched, isBindCloud]
  );

  // 在线支付内容
  const PayContent = useMemo(
    () => () => (
      <div>
        <Row gutter={[10, 20]}>
          <Col>
            功能1：客户下单时，当驿站或快递员开启支持在线支付，在提交订单时，可付款给驿站或快递员
          </Col>
          <Col>功能2：驿站或快递员在接单时可设置运费推送支付账单给用户，进行在线收款</Col>
          <Col>功能3：支持用户使用权益次卡、积分、优惠券在线抵扣运费</Col>
          <Col>
            <Row gutter={[0, 20]} style={{ textAlign: "center" }}>
              <Col>
                <Button onClick={() => onPayClick(open)} type="primary" loading={loadingOpenPay}>
                  {`${!open ? "开启" : "关闭"}`}
                  在线支付
                </Button>
              </Col>
              <Col>
                注：运费提现手续费5‰（微信收取，我方代扣）
                <a href="https://www.kuaidihelp.com/index/mail" target="_blank" rel="noreferrer">
                  查看说明
                </a>
              </Col>
            </Row>
          </Col>
        </Row>
      </div>
    ),
    [onPayClick, open, loadingOpenPay]
  );

  // 积分设置功能
  const ScoreSetting = useMemo(
    () => ({ list = [], isCheck, disabled, isBindCloud }) => (
      <Form>
        <List
          style={{ marginTop: "20px", marginBottom: "20px" }}
          bordered
          dataSource={list}
          renderItem={item => {
            const isOpened = item.status == 1; // 是否开启该积分功能
            return (
              <List.Item>
                <Row style={{ width: "100%" }} type="flex" justify="space-between" align="middle">
                  <Col>{item.content}</Col>
                  {item.type === "input" ? (
                    <Col>
                      <FormItem style={{ marginBottom: 0 }}>
                        {getFieldDecorator(item.name, {
                          initialValue: item.value,
                          rules: [{ max: 6, message: "最长不超过6个字符" }],
                        })(
                          <Input allowClear placeholder="请输入平台名称" style={{ width: 146 }} />
                        )}
                      </FormItem>
                    </Col>
                  ) : (
                    <Col>
                      <Row type="flex" align="middle" gutter={[10, 0]}>
                        <Col>赠送值：</Col>
                        <Col>
                          <FormItem style={{ marginBottom: 0 }}>
                            {getFieldDecorator(item.name, {
                              initialValue: item.value,
                            })(
                              <InputNumber
                                disabled={!isOpened}
                                min={0}
                                max={1000}
                                formatter={formatter}
                              />
                            )}
                          </FormItem>
                        </Col>
                        <Col>
                          <FormItem style={{ marginBottom: 0 }}>
                            {getFieldDecorator(`${item.name}_status`, {
                              initialValue: isOpened,
                              valuePropName: "checked",
                            })(
                              <Switch
                                checkedChildren="关"
                                unCheckedChildren="开"
                                onChange={() =>
                                  onCloseOrOpenScore(item.name, isOpened ? 2 : 1, item.value)
                                }
                              />
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                    </Col>
                  )}
                </Row>
              </List.Item>
            );
          }}
        />
        <Row>
          <Col>
            <FormItem style={{ marginBottom: 0 }}>
              {getFieldDecorator("isChecked", { initialValue: isCheck, valuePropName: "checked" })(
                <Checkbox
                  disabled={disabled}
                  onChange={onCheckBoxCheck}
                  style={{ marginRight: "10px" }}
                />
              )}
              公众号/小程序积分与快宝云店积分互通（用户在您的公众号/小程序和快宝云店内都可以核销积分）
            </FormItem>
          </Col>
          {isCheck &&
            (isBindCloud ? (
              <Col>
                与快宝云店：
                <span style={{ color: "#1890ff" }}>{scoreDetail.cloud_name || "--"}</span>
                积分已互通
                <span style={{ marginLeft: 10 }}>
                  <Popconfirm
                    title="解绑需要重新输入该云店账号密码，确定解绑？"
                    onConfirm={() => setIsBindCloud(false)}
                  >
                    <a>解绑</a>
                  </Popconfirm>
                </span>
              </Col>
            ) : (
              <Col>
                <Row type="flex">
                  <Col span={8}>
                    <FormItem>
                      {getFieldDecorator("account", {
                        rules: [
                          {
                            required: true,
                            message: "请输入快宝云店账号",
                          },
                        ],
                      })(
                        <>
                          <Input
                            onChange={e => onInputChange(e, "account")}
                            placeholder="请输入快宝云店账号"
                          />
                        </>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={8} push={1}>
                    <FormItem>
                      {getFieldDecorator("passWord", {
                        rules: [
                          {
                            required: true,
                            message: "请输入快宝云店密码",
                          },
                        ],
                      })(
                        <>
                          <Input.Password
                            onChange={e => onInputChange(e, "passWord")}
                            placeholder="请输入快宝云店密码"
                          />
                        </>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={8} push={2}>
                    <FormItem>
                      <Button
                        type="primary"
                        onClick={() => handleBind(scoreDetail.cloud_name ? 2 : 1)}
                      >
                        {scoreDetail.cloud_name ? "解绑" : "绑定"}
                      </Button>
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            ))}
          <Col span={24} style={{ textAlign: "center" }}>
            <Button type="primary" onClick={onSave}>
              保存设置
            </Button>
          </Col>
        </Row>
      </Form>
    ),
    [
      getFieldDecorator,
      handleBind,
      onCheckBoxCheck,
      onInputChange,
      onCloseOrOpenScore,
      onSave,
      scoreDetail,
    ]
  );

  // 积分内容
  const ScoreContent = useMemo(
    () => () => (
      <div>
        {!open ? (
          <Row gutter={[10, 20]}>
            <Col>1、价值固定比例：1积分=0.01元</Col>
            <Col>
              2、小程序/公众号新用户，首次绑定手机号，在线支付运费、云店同步积分可获取积分，在线支付时可抵扣运费
            </Col>
            <Col>3、公众号/小程序与快宝云店积分可互通，价值固定比例一致</Col>
            <Col>4、新零售平台积分对下属驿站适用，且积分由平台核销</Col>
            <Col>
              <Row gutter={[0, 20]} style={{ textAlign: "center" }}>
                <Col>
                  <Button onClick={() => openScore(open)} type="primary" loading={loadingOpenScore}>
                    开启积分功能
                  </Button>
                </Col>
                <Col>
                  注：运费提现手续费5‰（微信收取，我方代扣）
                  <a href="https://www.kuaidihelp.com/index/mail" target="_blank" rel="noreferrer">
                    查看说明
                  </a>
                </Col>
              </Row>
            </Col>
          </Row>
        ) : (
          <ScoreSetting
            list={listData}
            isCheck={isCheck}
            disabled={checkBoxDisabled}
            isBindCloud={isBindCloud}
          />
        )}
      </div>
    ),
    [open, openScore, loadingOpenScore, listData, isCheck, checkBoxDisabled, isBindCloud]
  );

  return (
    <Modal
      destroyOnClose
      visible={visible}
      title={title}
      onCancel={() => showModal(false)}
      footer={null}
      width="750px"
    >
      {type == "pay" ? <PayContent /> : <ScoreContent />}
    </Modal>
  );
};

SettingModal.propTypes = {
  type: propTypes.oneOf(["pay", "score"]).isRequired,
};

export default connect(({ loading }) => ({
  loadingOpenScore: loading.effects["wxSettings/wxOpenScore"],
  loadingOpenPay: loading.effects["wxSettings/wxOnlinePay"],
}))(React.memo(Form.create()(SettingModal)));
